import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

// 图片工具类
class ImageUtil {
  // 获取图片宽高
  static ui.Size getSize(String path) {
    int width = 0;
    int height = 0;
    Image image = Image.file(File(path));
    ImageStream? imageStream = image.image.resolve(const ImageConfiguration());
    ImageStreamListener imageStreamListener =
        ImageStreamListener((ImageInfo info, bool _) {
      debugPrint(
          'model  width: ${info.image.width}  height: ${info.image.height}');
      width = info.image.width;
      height = info.image.height;
    });
    imageStream.addListener(imageStreamListener);
    Future.delayed(const Duration(milliseconds: 1000)).then(
      (value) => imageStream.removeListener(imageStreamListener),
    );
    return ui.Size(width.toDouble(), height.toDouble());
  }

  // 获取本地视频缩略图
  static Future<String?> thumbnailVideoFile(String path) async {
    final fileName = await VideoThumbnail.thumbnailFile(
      video: path,
      thumbnailPath: (await getTemporaryDirectory()).path,
      imageFormat: ImageFormat.PNG,
      maxHeight:
          128, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
      quality: 25,
    );
    return fileName;
  }

  // 获取纯色图片
  static Future<ui.Image> createSolidColorImage(Color color,
      {int width = 1, int height = 1}) async {
    final recorder = ui.PictureRecorder();
    final canvas = ui.Canvas(recorder);
    final paint = ui.Paint()..color = color;
    canvas.drawRect(
        ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()), paint);
    final picture = recorder.endRecording();
    final img = await picture.toImage(width, height);
    return img;
  }
}
